package com.inifitness.common.rabbitmq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

/**
 * 延迟队列 使用ttl和dlx实现 Direct模式
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2023-02-01 17:05
 */
//@Configuration
public class DelayRabbitConfig {

  public static final String DELAY_QUEUE = "inifitness.delay.queue";

  public static final String DELAY_ROUTING_KEY = "inifitness.delay.key";

  public static final String DELAY_EXCHANGE = "inifitness.delay.exchange";

  public static final String DEAD_LETTER_QUEUE = "inifitness.dead.letter.queue";

  public static final String DEAD_LETTER_ROUTING_KEY = "inifitness.dead.letter.key";

  public static final String DEAD_LETTER_EXCHANGE = "inifitness.dead.letter.exchange";

  public static final int QUEUE_EXPIRATION = 3000;

  @Bean
  Queue delayQueue() {
    return QueueBuilder.durable(DELAY_QUEUE)
        //当前延时队列绑定的死信交换机，消息过期后丢入死信队列
        .withArgument("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE)
        //当前延时队列绑定的死信路由，消息过期后丢入死信队列
        .withArgument("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY)
        // 设置队列的过期时间
        .withArgument("x-message-ttl", QUEUE_EXPIRATION)
        .build();
  }

  @Bean
  Queue deadLetterQueue() {
    return QueueBuilder.durable(DEAD_LETTER_QUEUE)
        .build();
  }

  @Bean
  DirectExchange delayExchange() {
    return new DirectExchange(DELAY_EXCHANGE);
  }

  @Bean
  DirectExchange deadLetterExchange() {
    return new DirectExchange(DEAD_LETTER_EXCHANGE);
  }

  @Bean
  Binding delayBinding(@Qualifier("delayQueue") Queue delayQueue,
      @Qualifier("delayExchange") DirectExchange delayExchange) {
    return BindingBuilder.bind(delayQueue)
        .to(delayExchange)
        .with(DELAY_ROUTING_KEY);
  }

  @Bean
  Binding deadLetterBinding(@Qualifier("deadLetterQueue") Queue deadLetterQueue,
      @Qualifier("deadLetterExchange") DirectExchange deadLetterExchange) {
    return BindingBuilder.bind(deadLetterQueue)
        .to(deadLetterExchange)
        .with(DEAD_LETTER_ROUTING_KEY);
  }
}

